package com.ecloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import com.ecloud.gateway.global.GlobalConfig;

import reactor.core.publisher.Mono;

/**
 * 权限拦截器 这里建议只处理基础权限 防止非法请求进入下游
 *
 * @author LiuGangQiang Create in 2021/03/25
 */
@Configuration
public class SecurityFilter implements GlobalFilter, Ordered {

    /**
     * @see org.springframework.core.Ordered#getOrder()
     */
    @Override
    public int getOrder() {
        return GlobalConfig.SECURITY_FILTER_ORDER;
    }

    /**
     * @see org.springframework.cloud.gateway.filter.GlobalFilter#filter(org.springframework.web.server.ServerWebExchange, org.springframework.cloud.gateway.filter.GatewayFilterChain)
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /* 这里处理请求信息 */
        ServerHttpRequest request = exchange.getRequest();
        request = request.mutate().headers(header -> {
            /* TODO 这里根据请求头可以做认证处理 */
        }).build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        return chain.filter(build).then(Mono.fromRunnable(() -> {
            /* 这里处理返回结果 */
        }));
    }
}
